<?php

namespace app\api\controller;

use app\admin\model\Config;
use app\common\controller\ApiBase;
use app\Constant\ApiConstant;
use app\model\AgentShop;
use app\model\LiveGoods;
use app\model\LiveShare;
use app\model\Shop;
use app\model\Talent;
use think\facade\Request;
use Wechat\CommerceApp;

class Live extends ApiBase
{
    /**
     * 直播列表
     * @return \think\response\Json
     */
    public function list()
    {
        $page         = Request::get('page') ?: 1;
        $page_size    = Request::get('page_size') ?: 10;
        $index_status = Request::get('index_status', 0);
        $keyword      = Request::get('keyword');

        $query = \app\model\Live::field('id, appid, export_id, description, promoter_share_link, type, start_time, live_status, number')
            ->where('status', 1);
        if (!empty($index_status)) {
            $query->where('index_status', 1);
        }
        if (!empty($keyword)) {
            $appids        = [];
            $talent_appids = Talent::where('talent_nickname', 'like', "%{$keyword}%")->column('talent_appid');
            if ($talent_appids) {
                $appids = array_merge($appids, $talent_appids);
            }
            $shop_appids = AgentShop::where('appid', 'like', "%{$keyword}%")->column('appid');
            if ($shop_appids) {
                $appids = array_merge($appids, $shop_appids);
            }
            if (empty($appids)) {
                return $this->callback(ApiConstant::SUCCESS, 'success');
            }
            $query->where('appid', 'in', $appids);
        }
        $total = $query->count();

        $lists = $query
            ->withAttr('start_time', function ($value) {
                return $value > 0 ? date('Y-m-d H:i:s', $value) : '';
            })
            ->page($page, $page_size)
            ->order('sort', 'asc')
            ->order('id', 'desc')
            ->select();
        if ($lists) {
            $talent_ids = $shop_ids = [];
            foreach ($lists as $item) {
                if ($item['type'] == 1) {
                    $talent_ids[] = $item['appid'];
                } else {
                    $shop_ids[] = $item['appid'];
                }
            }
            $index_arr = [];
            if ($talent_ids) {
                $talents = Talent::where('talent_appid', 'in', $talent_ids)->column('talent_appid as appid, talent_nickname as name, talent_head_img as avatar');
                if ($talents) {
                    $index_arr = array_merge($index_arr, $talents);
                }
            }
            if ($shop_ids) {
                $shops = Shop::where('appid', 'in', $shop_ids)->column('appid, name, image as avatar');
                if ($shops) {
                    $index_arr = array_merge($index_arr, $shops);
                }
            }
            foreach ($lists as &$item) {
                $item['name']   = $index_arr[$item['appid']]['name'] ?? '';
                $item['avatar'] = $index_arr[$item['appid']]['avatar'] ?? '';
                $item['ratio']  = '20%-60%';
            }
        }

        $res = [
            'total' => $total,
            'list'  => $lists
        ];
        return $this->callback(ApiConstant::SUCCESS, 'success', $res);
    }

    public function info()
    {
        $id   = Request::get('id');
        $user = \app\model\User::field('id, level, sharer_appid')->where('token', $this->token)->find();
        if (empty($user)) {
            return $this->callback(ApiConstant::NO_LOGIN, '用户未登录');
        }
        $level = $user['level'];

        $info = \app\model\Live::field('id, appid, export_id, description, promoter_share_link, type, start_time, live_status, number, share_text')
            ->where('id', $id)
            ->withAttr('start_time', function ($value) {
                return $value > 0 ? date('Y-m-d H:i:s', $value) : '';
            })
            ->find();
        if (empty($info)) {
            return $this->callback(ApiConstant::FAILURE, '没有数据');
        }
        $name = $avatar = $promoter_share_link = '';
        try {
            $mini_program_appid = Config::where('name', 'wx_xcx_appid')->value('value');
            if ($info['type'] == 1) {
                $talent_info = Talent::field('id, talent_nickname, talent_head_img')->where('talent_appid', $info['appid'])->find();
                $name        = $talent_info['talent_nickname'];
                $avatar      = $talent_info['talent_head_img'];
                if ($info['live_status'] == 1) {
                    $live = CommerceApp::getInstance()->getLiveList($info['appid'], $mini_program_appid, $user['sharer_appid']);
                    if (!empty($live[0]['promoter_share_link'])) {
                        $promoter_share_link = $live[0]['promoter_share_link'];
                    }
                }
            } else {
                $shop_info = Shop::field('id, name, image')->where('appid', $info['appid'])->find();
                $name      = $shop_info['name'];
                $avatar    = $shop_info['image'];
            }
        } catch (\Exception $e) {
        }
        $info['name']                = $name;
        $info['avatar']              = $avatar;
        $info['promoter_share_link'] = $promoter_share_link;

        $goods         = LiveGoods::where('appid', $info['appid'])
            ->withAttr('product_price', function ($value) {
                return $value > 0 ? number_format($value / 100, 2) : '0.00';
            })
            ->select()->toArray();
        $info['goods'] = $goods;
        return $this->callback(ApiConstant::SUCCESS, 'success', $info);
    }

    public function qrcode()
    {
        $id   = Request::get('id');
        $user = \app\model\User::field('id, level, sharer_appid')->where('token', $this->token)->find();
        if (empty($user)) {
            return $this->callback(ApiConstant::NO_LOGIN, '用户未登录');
        }

        $info = $query = \app\model\Live::field('id, appid, export_id, type, live_status')
            ->where('id', $id)
            ->find();
        if (empty($info)) {
            return $this->callback(ApiConstant::FAILURE, '没有数据');
        }
        $qrcode = '';
        try {
            if ($info['type'] == 1) {
                if ($info['live_status'] == 1) {
                    $qrcode = CommerceApp::getInstance()->getLiveQrcode($info['appid'], $user['sharer_appid'], $info['export_id']);
                } else {
                    $qrcode = CommerceApp::getInstance()->getLiveNoticeQrCode($info['appid'], $user['sharer_appid'], $info['export_id']);
                }
            } else {

            }
        } catch (\Exception $e) {
        }
        return $this->callback(ApiConstant::SUCCESS, 'success', ['qrcode' => $qrcode]);
    }

    public function share()
    {
        $id   = Request::get('id');
        $user_id = \app\model\User::where('token', $this->token)->value('id');
        $share = LiveShare::where('user_id', $user_id)->where('live_id', $id)->
        value('id');
        if (!$share) {
            \app\model\Live::where('id', $id)->setInc('number');
            LiveShare::create([
                'user_id'  => $user_id,
                'live_id'  => $id,
            ]);
        }
        return $this->callback(ApiConstant::SUCCESS, '转发成功');
    }

}
